package com.itheima.service.mongo.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.RandomUtil;
import com.itheima.domain.mongo.Friend;
import com.itheima.domain.mongo.Sound;
import com.itheima.service.mongo.FriendService;
import com.itheima.vo.PageBeanVo;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@Service
public class FriendServiceImpl implements FriendService {
    @Autowired
    private MongoTemplate mongoTemplate;


    //保存好友关系(互相都是好友关系)
    @Override
    public void save(Long userId, Long friendId) {
        //1. 先判断userId和friendId是否已经是好友,如果不是,再添加
        Query query = new Query(Criteria.where("userId").is(userId).and("friendId").is(friendId));
        Friend friend1 = mongoTemplate.findOne(query, Friend.class);
        if (friend1 == null) {
            friend1 = new Friend();
            //如果为空，添加好友关系
            friend1.setUserId(userId);
            friend1.setFriendId(friendId);
            friend1.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friend1);
        }

        //2. 再判断friendId和userId是否已经是好友,如果不是,再添加
        Query query1 = new Query(Criteria.where("userId").is(friendId).and("friendId").is(userId));
        Friend friend2 = mongoTemplate.findOne(query1, Friend.class);
        if (friend2 == null) {
            friend2 = new Friend();
            //如果为空,添加好友关系
            friend2.setUserId(friendId);
            friend2.setFriendId(userId);
            friend2.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friend2);
        }

    }

    //根据登录用户分页查询自己的好友列表
    @Override
    public PageBeanVo findFriendById(Long userId, Integer pageNum, Integer pageSize) {
        Query query = new Query(Criteria.where("userId").is(userId)).skip((pageNum - 1) * pageSize).limit(pageSize);
        //查询出的好友列表
        List<Friend> friendList = mongoTemplate.find(query, Friend.class);
        //统计记录数
        long count = mongoTemplate.count(query, Friend.class);

        return new PageBeanVo(pageNum, pageSize, count, friendList);
    }

    @Override
    public void delete(Long userId, Long likeUserId) {
        //1. 删除我--它
        Query query1 = new Query(Criteria.where("userId").is(userId).and("friendId").is(likeUserId));
        mongoTemplate.remove(query1, Friend.class);

        //2. 删除它--我
        Query query2 = new Query(Criteria.where("userId").is(likeUserId).and("friendId").is(userId));
        mongoTemplate.remove(query2, Friend.class);

    }

    @Override
    public void saveVoice(Sound sound) {
        //保存用户语音信息
        sound.setCreated(System.currentTimeMillis());
        sound.setUpdated(System.currentTimeMillis());
        mongoTemplate.save(sound);
    }

    @Override
    //桃花传音  概率事件以用户为主  对于发送过语音的用户  平均概率查询、 本次采用平均分配
    public Sound getVoice(Long userId) {
        Sound sound = this.getSound(userId);
        if (sound == null) {
            //说明 数据被人更改了  需要重新获取id 重新获取值
            this.getSound(userId);
        } else if (sound.getStatus() == 0) {
            //没有漂流瓶
            return null;
        } else {
            sound.setStatus(0);
            sound.setUpdated(System.currentTimeMillis());
            mongoTemplate.save(sound);
            return sound;
        }
        return null;
    }
    //    桃花传音以 主键为主  概率事件为  语音发的越多    该用户越容易被收听
    private Sound getVoice1(Long userId) {
        //如果mongodb不考虑  不等于用户id===ne。userId  索引失效的问题
        //直接把所有条件拿到 查就号了
        Query query = new Query(
                Criteria.where("userId").ne(userId).and("status").is(1)
        );

        Long count = mongoTemplate.count(query, Sound.class);
        if (!count.equals(0L)) {
            //生成随机数
            int i = RandomUtil.randomInt(0, count.intValue());
            if (i==count&&i!=0){
                i--;
            }
            //拿数据
            Query limit = new Query(
                    Criteria.where("userId").ne(userId).and("status").is(1)
            ).skip(i).limit(1);
            Sound one = mongoTemplate.findOne(limit, Sound.class);
            one.setStatus(0);
            mongoTemplate.save(one);
            return one;
        }
        return null;
    }
    private Sound getSound(Long userId) {
        //1 去重查询语音信息表中 的userId----- //3 拿到帅选出的用户id的一条语音
        Query query = new Query(
                Criteria.where("status").is(1)
        );
        List<Long> toUserIdList = mongoTemplate.findDistinct(query, "userId", Sound.class, Long.class);
        //2 拿到id
        if (CollectionUtil.isNotEmpty(toUserIdList)) {
            //删除自己的id
            toUserIdList.remove(userId);
            //挑选id拿到值
            if (CollectionUtil.isNotEmpty(toUserIdList)) {
                Long toUserId = toUserIdList.get(RandomUtil.randomInt(toUserIdList.size()));
                //拿到数据
                Query query1 = new Query(
                        Criteria.where("userId").is(toUserId).and("status").is(1)
                ).skip(0).limit(1);
                return mongoTemplate.findOne(query1, Sound.class);
            }
            Sound sound = new Sound();
            sound.setStatus(0);
            return sound;
        }
        Sound sound = new Sound();
        sound.setStatus(0);
        return sound;
    }
}
